Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    feedbackType: 'feature',
    title: '',
    content: '',
    images: [],
    feedbackList: []
  },

  onLoad() {
    this.loadFeedbackList();
  },

  // 选择反馈类型
  selectType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({ feedbackType: type });
  },

  // 输入标题
  inputTitle(e) {
    this.setData({ title: e.detail.value });
  },

  // 输入内容
  inputContent(e) {
    this.setData({ content: e.detail.value });
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 3 - this.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // 上传图片
        this.uploadImages(res.tempFilePaths);
      }
    });
  },

  // 上传图片
  uploadImages(tempFilePaths) {
    const uploads = tempFilePaths.map(path => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: this.data.backendUrl + 'upload_feedback_image.php',
          filePath: path,
          name: 'image',
          success: res => {
            const data = JSON.parse(res.data);
            if (data.status === 'success') {
              resolve(data.image_url);
            } else {
              reject(data.message);
            }
          },
          fail: reject
        });
      });
    });

    wx.showLoading({ title: '上传中...' });
    Promise.all(uploads).then(urls => {
      this.setData({
        images: [...this.data.images, ...urls]
      });
      wx.hideLoading();
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: '上传失败',
        icon: 'none'
      });
    });
  },

  // 删除图片
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images;
    images.splice(index, 1);
    this.setData({ images });
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url;
    const urls = this.data.images.map(img => this.data.backendUrl + img);
    wx.previewImage({
      current: url,
      urls: urls
    });
  },

  // 提交反馈
  submitFeedback() {
    const { feedbackType, title, content, images } = this.data;
    
    // 验证必填字段
    if (!title.trim()) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      });
      return;
    }
    if (!content.trim()) {
      wx.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      });
      return;
    }

    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 准备提交的数据
    const submitData = {
      user_id: userInfo.id,
      type: feedbackType,
      title: title.trim(),
      content: content.trim(),
      images: images.length > 0 ? images.join(',') : ''  // 如果没有图片就提交空字符串
    };

    wx.request({
      url: this.data.backendUrl + 'submit_feedback.php',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: submitData,
      success: (res) => {
        if (res.data.status === 'success') {
          wx.showToast({
            title: '提交成功',
            icon: 'success'
          });
          // 重置表单
          this.setData({
            title: '',
            content: '',
            images: []
          });
          // 刷新列表
          this.loadFeedbackList();
        } else {
          wx.showToast({
            title: res.data.message || '提交失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // 加载反馈列表
  loadFeedbackList() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) return;

    wx.request({
      url: this.data.backendUrl + 'get_feedback_list.php',
      data: { user_id: userInfo.id },
      success: (res) => {
        if (res.data.status === 'success') {
          // 反馈列表中的图片也需要拼接完整路径
          const feedbackList = res.data.list.map(item => {
            if (item.images && item.images.length > 0) {
              item.images = item.images.map(img => this.data.backendUrl + img);
            }
            return item;
          });
          this.setData({
            feedbackList: feedbackList.slice(0, 3)
          });
        }
      }
    });
  },

  // 查看反馈详情
  viewFeedbackDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/feedback-detail/feedback-detail?id=${id}`
    });
  },

});
